package com.work.work.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.work.work.common.R;
import com.work.work.dto.TeamMemberDTO;
import com.work.work.entity.Team;
import com.work.work.service.TeamService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Tag(name = "团队管理")
@RestController
@RequestMapping("/team")
public class TeamController {
    @Autowired
    private TeamService teamService;

    @Operation(summary = "创建团队")
    @PostMapping("/create")
    public R<Team> createTeam(@RequestBody Team team) {
        if (team.getTeamname() == null || team.getTeamname().trim().isEmpty()) {
            return R.fail("团队名称不能为空");
        }
        return teamService.createTeam(team) ? R.ok(team, "项目创建成功") : R.fail("创建团队失败");
    }

    @Operation(summary = "更新团队信息")
    @PutMapping("/{id}")
    public R<Boolean> updateTeam(@PathVariable Integer id, @RequestBody Team team) {
        team.setId(id);
        return teamService.updateTeam(team) ? R.ok(true, "项目创建成功") : R.fail("更新团队失败");
    }

    @Operation(summary = "更新团队信息")
    @PutMapping("/update")
    public R<Boolean> updateTeam(@RequestBody Team team) {
        if (team.getId() == null) {
            return R.fail("团队ID不能为空");
        }
        if (team.getTeamname() == null || team.getTeamname().trim().isEmpty()) {
            return R.fail("团队名称不能为空");
        }

        return teamService.updateTeam(team) ? R.ok(true, "更新团队成功") : R.fail("更新团队失败");
    }

    @Operation(summary = "获取团队详情")
    @GetMapping("/{id}")
    public R<Team> getTeamById(@PathVariable Integer id) {
        Team team = teamService.getById(id);
        return team != null ? R.ok(team, "项目创建成功") : R.fail("团队不存在");
    }

    @Operation(summary = "分页获取团队列表")
    @GetMapping("/page")
    public R<Page<Team>> getTeamList(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size) {
        return R.ok(teamService.getTeamList(current, size), "项目创建成功");
    }

    @Operation(summary = "获取所有团队")
    @GetMapping("/all")
    public R<List<Team>> getAllTeams() {
        return R.ok(teamService.getAllTeams(), "项目创建成功");
    }


    @Operation(summary = "获取团队成员列表")
    @GetMapping("/{id}/members")
    public R<List<TeamMemberDTO>> getTeamMembers(@PathVariable Integer id) {
        if (id == null) {
            return R.fail("团队ID不能为空");
        }

        // 检查团队是否存在
        Team team = teamService.getById(id);
        if (team == null) {
            return R.fail("团队不存在");
        }

        List<TeamMemberDTO> members = teamService.getTeamMembers(id);
        return R.ok(members, "项目创建成功");
    }
}